//
//  main.m
//  DownLoad
//
//  Created by henry on 7/4/2019.
//  Copyright © 2019 何如意. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        
        NSData *data = [NSData dataWithContentsOfFile:@"/Users/heruyi/Desktop/iOS /Demo/DownLoad/DownLoad/urls_porn.txt"];
        NSString *images = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        NSArray *imgs = [images componentsSeparatedByString:@"\n"];
        NSURLSession *session = [NSURLSession sharedSession];
        dispatch_semaphore_t sem = dispatch_semaphore_create(5);
        for (int i=0; i<100; i++) {
            dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
            NSURL *ral = [NSURL URLWithString:imgs[i]];
            NSURLRequest *req = [[NSURLRequest alloc]initWithURL:ral cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
            [[session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                
                if (!error) {
                    NSString *path = [NSString stringWithFormat:@"/Users/heruyi/Desktop/porn/%@%@",[[[NSUUID UUID]UUIDString] substringToIndex:6],response.URL.lastPathComponent];
                    NSError *err = nil;
                    [[NSFileManager defaultManager]copyItemAtPath:location.path toPath:path error:&err];
                    if (err) {
                        NSLog(@"%@", err.debugDescription);
                    }
                }else{
                     NSLog(@"%@", error.debugDescription);
                }
                NSLog(@"第%d个请求完成",i);
                dispatch_semaphore_signal(sem);
            }]resume];
        }
        NSLog(@"循环完成");
    }
    [[NSRunLoop currentRunLoop]run];
    return 0;
}
